package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

// 全局处理异常
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //重复异常
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultInfo duplicateKeyExceptionHandler(Exception ex) {
        // 1.日志记录异常
        log.error(ex.getMessage());
        // 2. 返回结果
        return ResultInfo.error("操作失败:名称重复定义");
    }

    //预期的异常
    @ExceptionHandler(CustomException.class)
    public ResultInfo exceptionHandler(CustomException ex) {
        //日志
        log.error(ex.getMessage());
        //返回逻辑重定义的错误提示
        return ResultInfo.error(ex.getMessage());
    }

    //非预期异常
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionHandler(Exception ex) {
        //日志
        log.error(ex.getMessage());
        //返回一个固定异常
        return ResultInfo.error("对不起,您的网络有问题,请稍后再试");
    }

}
